package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.DailyCommend;
import cn.wolfcode.trip.base.domain.DailyCommendContent;
import cn.wolfcode.trip.base.mapper.DailyCommendContentMapper;
import cn.wolfcode.trip.base.mapper.DailyCommendMapper;
import cn.wolfcode.trip.base.query.DailyCommendQueryObject;
import cn.wolfcode.trip.base.service.IDailyCommendService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class DailyCommendServiceImpl implements IDailyCommendService {
    @Autowired
    private DailyCommendMapper dailyCommendMapper;

    @Autowired
    private DailyCommendContentMapper contentMapper;


    @Override
    public void save(DailyCommend dailyCommend) {

    }

    @Override
    public PageInfo query(DailyCommendQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<DailyCommend> list = dailyCommendMapper.queryForList(qo);
        return new PageInfo(list);
    }



    @Override
    public void delete(Long id) {
        dailyCommendMapper.deleteByPrimaryKey(id);
    }

    @Override
    public DailyCommend get(Long id) {
        return dailyCommendMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<DailyCommend> selectAll() {
        return dailyCommendMapper.selectAll();
    }

    @Override
    public void saveOrUpdate(DailyCommend dailyCommend) {
        //判断优先度是否为空
        if (dailyCommend.getSequence() == null) {
            //如果优先度没有写设置优先度最低,数值越大,优先度越低
            int sequence = dailyCommendMapper.getSequence(dailyCommend.getType());
            //设置优先度
            dailyCommend.setSequence(sequence +1);
        }
        //设置推荐时间
        dailyCommend.setSchedule(new Date());
        //判断推荐日报对象是否为空
        if (dailyCommend.getId() != null) {
            //不为空,获取日报对象的内容对象
            DailyCommendContent commendContent = dailyCommend.getCommendContent();
            //更新日报对象的内容,同时也更新内容对象
            dailyCommendMapper.updateByPrimaryKey(dailyCommend);
            contentMapper.updateByPrimaryKey(commendContent);
        } else {
            //首先保存推荐日报对象
            dailyCommendMapper.insert(dailyCommend);
            //获取推荐日报内容对象,并设置对应的id值
            DailyCommendContent commendContent = dailyCommend.getCommendContent();
            commendContent.setId(dailyCommend.getId());
            //保存推荐日报内容对象
            contentMapper.insert(commendContent);
        }

    }

    @Override
    public DailyCommendContent getContentByDailyCommendId(Long daliyCommendId) {
        return contentMapper.selectByPrimaryKey(daliyCommendId);
    }

    @Override
    public List<DailyCommend> getDailyCommendsByUserId(Long userId) {
        return dailyCommendMapper.selectDailyCommendsByUserId(userId);
    }


}
